package org.xqh.test.ugreen.showdoc;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.arronlong.httpclientutil.HttpClientUtil;
import com.arronlong.httpclientutil.common.HttpConfig;
import com.arronlong.httpclientutil.common.HttpHeader;
import com.arronlong.httpclientutil.common.HttpResult;
import com.arronlong.httpclientutil.exception.HttpProcessException;
import org.apache.http.Header;
import org.springframework.util.CollectionUtils;
import org.xqh.utils.file.ReadTxtFileUtils;
import org.xqh.utils.http.FxHttpClientUtils;

import java.io.File;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName FixShowDocFileUrl
 * @Description TODO
 * @Author xuqianghui
 * @Date 2023/12/20 17:26
 * @Version 1.0
 */
public class FixShowDocFileUrl {
    private static final String regex = "\\((http://showdoc.ugreengroup.com:([0-9]+)/server/.*[^)])\\)";
    private static final Pattern pattern = Pattern.compile(regex);
    private static final String cookie = "PHPSESSID=c502b82a7b8ff34c3af24470ae540342; think_language=zh-CN";

    public static void main(String[] args) {
//
        fixOneShowDocFile("D:\\test\\showdoc\\1.txt");
    }


    private static void fixOneShowDocFile(String filePath){
        String html = ReadTxtFileUtils.readAllTxt(new File(filePath));
        Matcher m = pattern.matcher(html);
        while (m.find()){
            int port = Integer.parseInt(m.group(2));
            String url = m.group(1);//完整的url
            String okUrl = getOkUrl(url, port);
            html = html.replace(url, okUrl);//替换url 并写入文件
        }
    }

    private static String getOkUrl(String url, int port){
        if (port != 4999){
            url = url.replace(String.format(":%s", port), ":4999");
        }

//        url = url.replace("showdoc.ugreengroup.com", "198.18.0.6");
        //198.18.0.6:4999
        System.out.println("=====> "+url);
        //访问地址 获取 响应头
        HttpRequest httpRequest = HttpUtil.createGet(url);
        httpRequest.cookie(cookie);
        try (HttpResponse httpResponse = httpRequest.execute()) {
            System.out.println(httpResponse.getStatus());

//            String newUrl = httpResponse.getResp().getFirstHeader("Location").getName();
//            System.out.println("new url ==> " + newUrl);
//            return newUrl;
            return null;
        }

    }

    private static  Header[] getReqHeaders(){
        return HttpHeader.custom()
                .cookie(cookie)
                .build();
    }


}

